package com.un.ebs.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @email 496382223@qq.com
 * @author:Lijj
 * @date: 2019/7/24
 */
public class WebUtils {
    /**
     * 当正确时返回的值
     * @param data
     * @return
     */
    public static<T> WebResult success(T data){
        return success(0,data);
    }

    /**
     * 当正确时返回的值
     * @param code
     * @param data
     * @return
     */
    public static<T> WebResult success(int code, T data){
        WebResult result = new WebResult();
        result.setCode(code);
        result.setMessage(null);
        result.setData(data);
        return result;
    }

    public static<T> WebResult success(int code,String message, T data){
        WebResult result = new WebResult();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data);
        return result;
    }

    /**
     * 当错误返回的值
     * @return
     */
    public static WebResult success(){
        return success(null);
    }

    /**
     * 当错误时返回的值
     * @param code
     * @param msg
     * @return
     */
    public static<T> WebResult error(int code, String msg,T data){
        WebResult result = new WebResult();
        result.setCode(code);
        result.setMessage(msg);
        result.setData(data);
        return result;
    }

    public static WebResult error(int code,String msg){
        return error(code,msg,null);
    }

    public static WebResult error(Exception ex){
        WebResult result = new WebResult();
        result.setCode(ex.hashCode());
        result.setMessage(ex.getMessage());
        return result;
    }

    /**
     * 序列化成JsonString
     * @param webResult
     * @return
     * @throws JsonProcessingException
     */
    public static String getString(WebResult webResult) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writeValueAsString(webResult);
    }

    public static void sendMessage(HttpServletResponse response, String message) throws IOException {
        sendMessage(response,-1,message,null);
    }
    public static<T> void sendMessage(HttpServletResponse response, int code, String message,T data) throws IOException {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setDateHeader("Expires", 0);
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        WebResult result = WebUtils.error(code,message,data);
        response.getWriter().write(WebUtils.getString(result));
    }
}
